<template>
	<view class="chat-container">
		<!-- 顶部导航栏 -->
		<view class="chat-header">
			<view class="header-left" @tap="goBack">
				<text class="iconfont icon-back"></text>
			</view>
			<text class="header-title">智慧农业助手</text>
		</view>

		<!-- 聊天记录区域 -->
		<scroll-view class="chat-list" scroll-y :scroll-top="scrollTop" @scrolltoupper="loadMore">
			<view class="chat-item" v-for="(item, index) in chatList" :key="index"
				:class="{'chat-item-ai': !item.isUser, 'chat-item-user': item.isUser}">
				<view class="avatar">
					<image :src="item.isUser ? '/static/deep.jpg' : '/static/deep.jpg'"></image>
				</view>
				<view class="message">
					<view class="content">{{item.content}}</view>
					<view class="time">{{item.time}}</view>
				</view>
			</view>
		</scroll-view>

		<!-- 输入区域 -->
		<view class="input-area">
			<view class="input-box">
				<textarea v-model="inputContent" class="input" :adjust-position="false" :cursor-spacing="20"
					placeholder="请输入您想咨询的农业相关问题..." @confirm="sendMessage" />
				<button class="send-btn" @click="sendMessage" :disabled="!inputContent.trim()">发送</button>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			chatList: [], // 聊天记录
			inputContent: '', // 输入内容
			scrollTop: 0, // 滚动条位置
			isLoading: false // 是否正在加载
		}
	},
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack({
				delta: 1
			});
		},
		// 格式化时间
		formatTime(date) {
			const pad = (num) => num.toString().padStart(2, '0');
			
			const year = date.getFullYear();
			const month = pad(date.getMonth() + 1);
			const day = pad(date.getDate());
			const hours = pad(date.getHours());
			const minutes = pad(date.getMinutes());
			const seconds = pad(date.getSeconds());
			
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
		},

		// 发送消息
		async sendMessage() {
			if (!this.inputContent.trim() || this.isLoading) return;
			
			const userMessage = this.inputContent.trim();
			const timestamp = this.formatTime(new Date());
			
			// 添加用户消息到列表
			this.chatList.push({
				content: userMessage,
				time: timestamp,
				isUser: true
			});
			
			this.inputContent = '';
			this.isLoading = true;
			
			try {
				// 调用云函数获取AI回复
				const response = await uniCloud.callFunction({
					name: 'deepseek-chat',
					data: {
						message: userMessage
					}
				});
				
				if (!response.result.success) {
					throw new Error(response.result.error || '请求失败');
				}
				
				// 添加AI回复到列表
				this.chatList.push({
					content: response.result.reply,
					time: this.formatTime(new Date()),
					isUser: false
				});
			} catch (error) {
				// 显示具体的错误信息
				uni.showToast({
					title: error.message || '发送失败，请重试',
					icon: 'none',
					duration: 3000
				});
				
				// 添加错误提示到聊天列表
				this.chatList.push({
					content: '抱歉，发生了一些错误，请稍后重试。',
					time: this.formatTime(new Date()),
					isUser: false
				});
			} finally {
				this.isLoading = false;
				this.scrollToBottom();
			}
		},
		
		// 滚动到底部
		scrollToBottom() {
			setTimeout(() => {
				const query = uni.createSelectorQuery().in(this);
				query.select('.chat-list').boundingClientRect(data => {
					this.scrollTop = data.height;
				}).exec();
			}, 100);
		},
		
		// 加载更多历史记录
		loadMore() {
			// TODO: 实现加载历史记录功能
		}
	},
	// 添加欢迎消息
	mounted() {
		const welcomeMessage = {
			content: '您好！很高兴为您提供农业方面的咨询服务。请问您需要了解农作物种植、病虫害防治、土壤改良，还是其他农业相关问题的建议呢？我会用简单易懂的方式为您解答。',
			time: this.formatTime(new Date()),
			isUser: false
		};
		this.chatList.push(welcomeMessage);
	}
}
</script>

<style lang="scss">
.chat-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f7fa;
	
	.chat-header {
		padding: 20rpx 30rpx;
		background-color: #4CAF50;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		display: flex;
		align-items: center;
		position: relative;
		
		.header-left {
			position: absolute;
			left: 30rpx;
			top: 50%;
			transform: translateY(-50%);
			padding: 10rpx;
			
			.iconfont {
				font-size: 40rpx;
				color: #ffffff;
			}
		}
		
		.header-title {
			flex: 1;
			font-size: 36rpx;
			font-weight: bold;
			color: #ffffff;
			text-align: center;
		}
	}
	
	.chat-list {
		flex: 1;
		padding: 30rpx;
		
		.chat-item {
			display: flex;
			margin-bottom: 40rpx;
			
			.avatar {
				width: 80rpx;
				height: 80rpx;
				margin-right: 24rpx;
				flex-shrink: 0;
				
				image {
					width: 100%;
					height: 100%;
					border-radius: 50%;
					box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
				}
			}
			
			.message {
				max-width: 70%;
				
				.content {
					padding: 24rpx;
					border-radius: 20rpx;
					background-color: #fff;
					word-break: break-all;
					font-size: 28rpx;
					line-height: 1.6;
					box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
				}
				
				.time {
					font-size: 24rpx;
					color: #999;
					margin-top: 12rpx;
					padding: 0 10rpx;
				}
			}
			
			&.chat-item-ai {
				.message .content {
					background-color: #e8f5e9;
					color: #2e7d32;
				}
			}
			
			&.chat-item-user {
				flex-direction: row-reverse;
				
				.avatar {
					margin-right: 0;
					margin-left: 24rpx;
				}
				
				.message {
					.content {
						background-color: #4CAF50;
						color: #ffffff;
					}
					
					.time {
						text-align: right;
					}
				}
			}
		}
	}
	
	.input-area {
		padding: 20rpx 30rpx;
		background-color: #fff;
		border-top: 2rpx solid #eee;
		
		.input-box {
			display: flex;
			align-items: flex-end;
			
			.input {
				flex: 1;
				min-height: 80rpx;
				max-height: 160rpx;
				padding: 20rpx;
				border-radius: 16rpx;
				background-color: #f5f7fa;
				font-size: 28rpx;
				margin-right: 20rpx;
			}
			
			.send-btn {
				width: 120rpx;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				background-color: #4CAF50;
				color: #fff;
				border-radius: 16rpx;
				font-size: 28rpx;
				padding: 0;
				
				&[disabled] {
					background-color: #a5d6a7;
					opacity: 0.7;
				}
				
				&:active {
					transform: scale(0.98);
				}
			}
		}
	}
}

// 适配底部安全区
.chat-container {
	padding-bottom: constant(safe-area-inset-bottom);
	padding-bottom: env(safe-area-inset-bottom);
}
</style> 